<template>
  <div class="setting-sub-manage-container" :style="{padding:showNav?'16px':'0'}">
    <div v-if="showNav" class="left-menu">
      <div class="menu-title">消息设置</div>
      <div v-for="(item, index) in newMenuList" :key="index">
        <nav :class="`menu-list ${nowMenu == index ? 'menu-checked' : ''}`" @click="changePage(item, index)">
          <div class="icon-box">
            <i :class="`iconfont ${item.icon} ${nowMenu == index ? 'font-16 font-w-600' : 'font-14'}`"></i>
          </div>
          <span>{{ item.name }}</span>
        </nav>
      </div>
    </div>
    <div class="main">
      <div class="setting-sub-manage" style="padding:12px 16px;">
        <p class="tip">当订阅某个视图后，如果该视图有新工单产生，则会发送一条消息来通知所有订阅了该视图的成员。</p> 
        您可以点击下方相应的选择框空白处来添加订阅成员，同时在相应列表页面也有单独的订阅按钮方便成员自主订阅。
      </div>

      <!-- 待分配工单订阅管理 -->
      <div class="setting-sub-manage">
        <div class="setting-title-content">
          待分配工单订阅管理
          <el-tooltip content="请确保订阅待分配通知的用户具备查看全部工单的权限" placement="top">
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip>
        </div>
        <div class="setting—box-multiple">
          <base-select
            v-model="allotSubList"
            :remote-method="remoteMethodList"
            @input="updateUser($event, 'allotSubList')"
            multiple
            clearable
            is-use-value
            placeholder="请选择"
          >
            <template slot="option" slot-scope="{option}">
              <div>
                <template v-if="isOpenData && option.staffId">
                  <open-data :openid="option.staffId"></open-data>
                </template>
                <template v-else>{{option.label}}</template>
              </div>
            </template>
          </base-select>
          <el-button class="multiple-save" type="primary" @click="saveSubManage('allotSubList')" :disabled="pending">保存</el-button>
        </div>
      </div>
      <!-- 待分配工单订阅管理 -->
    
      <!-- 工单池订阅管理 -->
      <div class="setting-sub-manage">
        <div class="setting-title-content">
          工单池订阅管理
          <el-tooltip placement="top">
            <div slot="content">
              <p></p>
              <p>1、如果启用了按客户服务部门划分工单池，则订阅人只能接收到他所在部门的客户的订阅通知；</p>
              <p>2、如果设置了工单类型的可用部门，则只有属于工单类型可见部门的订阅人可以收到该工单类型的订阅通知；</p>
              <p>3、如果启用了按客户服务部门划分工单池且设置了工单类型的可用部门，则只有同时满足两者的订阅人可以收到该工单类型的订阅通知</p>
            </div>
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip>
        </div>
        <div class="setting—box-multiple">
          <base-select
            v-model="poolSubList"
            :remote-method="remoteMethodList"
            @input="updateUser($event, 'poolSubList')"
            multiple
            clearable
            is-use-value
            placeholder="请选择"
          >
            <template slot="option" slot-scope="{option}">
              <div>
                <template v-if="isOpenData && option.staffId">
                  <open-data :openid="option.staffId"></open-data>
                </template>
                <template v-else>{{option.label}}</template>
              </div>
            </template>
          </base-select>
          <el-button class="multiple-save" type="primary" @click="saveSubManage('poolSubList')" :disabled="pending">保存</el-button>
        </div>
      </div>
      <!-- 工单池订阅管理 -->
 
      <!-- 待结算工单订阅管理 -->
      <div class="setting-sub-manage">
        <div class="setting-title-content">
          待结算工单订阅管理
          <el-tooltip content="请确保订阅待结算的用户具备工单结算权限" placement="top">
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip>
        </div>
        <div class="setting—box-multiple">
          <base-select
            v-model="auditSubList"
            :remote-method="remoteMethodList"
            @input="updateUser($event, 'auditSubList')"
            multiple
            clearable
            is-use-value
            placeholder="请选择"
          >
            <template slot="option" slot-scope="{option}">
              <div>
                <template v-if="isOpenData && option.staffId">
                  <open-data :openid="option.staffId"></open-data>
                </template>
                <template v-else>{{option.label}}</template>
              </div>
            </template>
          </base-select>
          <el-button class="multiple-save" type="primary" @click="saveSubManage('auditSubList')" :disabled="pending">保存</el-button>
        </div>
      </div>
      <!-- 待结算工单订阅管理 -->

      <!-- 待回访工单订阅管理 -->
      <div class="setting-sub-manage">
        <div class="setting-title-content">
          待回访工单订阅管理
          <el-tooltip content="请确保订阅待回访的用户具备工单回访权限" placement="top">
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip>
        </div>
        <div class="setting—box-multiple">
          <base-select
            v-model="reviewSubList"
            :remote-method="remoteMethodList"
            @input="updateUser($event, 'reviewSubList')"
            multiple
            clearable
            is-use-value
            placeholder="请选择"
          >
            <template slot="option" slot-scope="{option}">
              <div>
                <template v-if="isOpenData && option.staffId">
                  <open-data :openid="option.staffId"></open-data>
                </template>
                <template v-else>{{option.label}}</template>
              </div>
            </template>
          </base-select>
          <el-button class="multiple-save" type="primary" @click="saveSubManage('reviewSubList')" :disabled="pending">保存</el-button>
        </div>
      </div>
      <!-- 待回访工单订阅管理 -->

      <!-- 管理员汇总日报 -->
      <div class="setting-sub-manage">
        <div class="setting-title-content">
          管理员汇总日报
          <el-tooltip placement="top">
            <div slot="content">
              <p></p>
              <p>管理员汇总日报-数据说明</p>
              <p v-for="item in queryList" :key="item.id">
                <span v-if="item.module == 'manager'">{{item.name}}：{{item.description}}</span>
              </p>
              如需节假日不发送通知，请到系统管理-工作信息中维护
            </div>
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip>
        </div>

        <el-form label-position="top" class="report-department">
          <el-form-item>
            <el-dropdown trigger="click" placement="bottom-start">
              <div class="cur-point">
                <span>{{manager.group == 'role' ? '按角色' : '按部门'}}</span>
                <i class="iconfont icon-caret-down"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span @click="selectRoleOrTag('role', 'manager')">按角色</span>
                </el-dropdown-item>
                <el-dropdown-item>
                  <span @click="selectRoleOrTag('tag', 'manager')">按部门</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          
            <template v-if="manager.group == 'role'">
              <el-select v-model="manager.groupIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in roles"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                >
                </el-option>
              </el-select> 
            </template> 
            <template v-else>
              <biz-team-select :value="manager.groupIds" multiple @input="update($event, 'manager')" :fetch-func="fetchTeam" placeholder="请选择接收部门，接收部门为空时不发送"/>
            </template> 

          </el-form-item>
        
          <el-form-item label="通知中的信息">
            <el-select v-model="manager.mainQueryKeys" @change="mainQueryKeysHandler($event, 'manager')" multiple placeholder="请选择">
              <el-option
                v-for="item in queryManagerList"
                :label="item.name"
                :value="item.queryKey"
                :key="item.id"
              >
              </el-option>
            </el-select> 
          </el-form-item>
          <el-form-item label="链接页面中的信息">
            <el-select v-model="manager.queryKeys" @change="queryKeysHandler($event, 'manager')" multiple placeholder="请选择">
              <el-option
                v-for="item in queryManagerList"
                :label="item.name"
                :value="item.queryKey"
                :key="item.id"
              >
              </el-option>
            </el-select> 
          </el-form-item>
          <div class="save-report">
            <el-button type="primary" @click="saveReport('manager')" :disabled="pending">保存</el-button>
          </div>
        </el-form>
     
      </div>
      <!-- 管理员汇总日报 -->

      <!-- 部门汇总日报 -->
      <div class="setting-sub-manage">
        <div class="setting-title-content">
          部门汇总日报
          <el-tooltip placement="top">
            <div slot="content">
              <p></p>
              <p>管理员汇总日报-数据说明</p>
              <p v-for="item in queryList" :key="item.id">
                <span v-if="item.module == 'tag'">{{item.name}}：{{item.description}}</span>
              </p>
              如需节假日不发送通知，请到系统管理-工作信息中维护
            </div>
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip>
        </div>

        <el-form label-position="top" class="report-department">
          <el-form-item label="发送通知的部门">
            <biz-team-select :value="tag.groupIds" multiple @input="update($event, 'tag')" :fetch-func="fetchTeam" placeholder="请选择接收部门，接收部门为空时不发送"/>
          </el-form-item>
          <el-form-item label="通知中的信息">
            <el-select v-model="tag.mainQueryKeys" @change="mainQueryKeysHandler($event, 'tag')" multiple placeholder="请选择">
              <el-option
                v-for="item in queryTagList"
                :label="item.name"
                :value="item.queryKey"
                :key="item.id"
              >
              </el-option>
            </el-select>                          
          </el-form-item>
          <el-form-item label="链接页面中的信息">
            <el-select v-model="tag.queryKeys" @change="queryKeysHandler($event, 'tag')" multiple placeholder="请选择">
              <el-option
                v-for="item in queryTagList"
                :label="item.name"
                :value="item.queryKey"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <div class="save-report">
            <el-button type="primary" @click="saveReport('tag')" :disabled="pending">保存</el-button>
          </div>
        </el-form>
      
      </div>
      <!-- 部门汇总日报 -->

      <!-- 个人日报 -->
      <div class="setting-sub-manage">
        <div class="setting-title-content">
          个人日报
          <el-tooltip placement="top">
            <div slot="content">
              <p></p>
              <p>个人日报-数据说明</p>
              <p v-for="item in queryList" :key="item.id">
                <span v-if="item.module == 'personal'">{{item.name}}：{{item.description}}</span>
              </p>
              如需节假日不发送通知，请到系统管理-工作信息中维护
            </div>
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip>
        </div>

        <el-form label-position="top" class="report-department">
          <el-form-item>
            <el-dropdown trigger="click" placement="bottom-start">
              <div class="cur-point">
                <span>{{personal.group == 'role' ? '按角色' : '按部门'}}</span>
                <i class="iconfont icon-caret-down"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span @click="selectRoleOrTag('role', 'personal')">按角色</span>
                </el-dropdown-item>
                <el-dropdown-item>
                  <span @click="selectRoleOrTag('tag', 'personal')">按部门</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          
            <template v-if="personal.group == 'role'">
              <el-select v-model="personal.groupIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in roles"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                >
                </el-option>
              </el-select> 
            </template>
            <template v-else>
              <biz-team-select :value="personal.groupIds" multiple @input="update($event, 'personal')" :fetch-func="fetchTeam" placeholder="请选择接收部门，接收部门为空时不发送"/>
            </template>

          </el-form-item>

          <el-form-item label="通知中的信息">
            <el-select v-model="personal.mainQueryKeys" @change="mainQueryKeysHandler($event, 'personal')" multiple placeholder="请选择">
              <el-option
                v-for="item in queryPersonalList"
                :label="item.name"
                :value="item.queryKey"
                :key="item.id"
              >
              </el-option>
            </el-select>                          
          </el-form-item>
          <el-form-item label="链接页面中的信息">
            <el-select v-model="personal.queryKeys" @change="queryKeysHandler($event, 'personal')" multiple placeholder="请选择">
              <el-option
                v-for="item in queryPersonalList"
                :label="item.name"
                :value="item.queryKey"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <div class="save-report">
            <el-button type="primary" @click="saveReport('personal')" :disabled="pending">保存</el-button>
          </div>
        
        </el-form>
      
      </div>

      <div class="setting-sub-manage" v-if="isQrcodeSetting">
        <div class="setting-title-content">
          超级二维码行为分析报告
          <el-tooltip placement="top">
            <div slot="content">
              <p></p>
              <p v-for="item in queryList" :key="item.id">
                <span v-if="item.module == 'qrcode'">{{item.name}}：{{item.description}}</span>
              </p>
            </div>
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip>
        </div>

        <el-form label-position="top" class="report-department">
          <el-form-item>
            <el-dropdown trigger="click" placement="bottom-start">
              <div class="cur-point">
                <span>{{qrcode.group == 'role' ? '按角色' : '按人员'}}</span>
                <i class="iconfont icon-caret-down"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <span @click="selectRoleOrTag('role', 'qrcode')">按角色</span>
                </el-dropdown-item>
                <el-dropdown-item>
                  <span @click="selectRoleOrTag('person', 'qrcode')">按人员</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          
            <template v-if="qrcode.group == 'role'">
              <el-select v-model="qrcode.groupIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in roles"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                >
                </el-option>
              </el-select> 
            </template>
            <template v-else>
                <!-- <biz-remote-select
                  :value="qrcode.userList"
                  :remote-method="remoteMethodList"
                  @input="update($event, 'qrcode')"
                  placeholder="请选择"
                  value-key="userId"
                  multiple
                  filterable
                  remote
                >
                </biz-remote-select> -->
              <base-select
                class="base-select-wrap"
                v-model="qrcode.userList"
                :remote-method="remoteMethodList"
                @input="updateUser($event, 'qrcode')"
                multiple
                clearable
                is-use-value
                placeholder="请选择"
              >
                <template slot="option" slot-scope="{option}">
                  <div>
                    <template v-if="isOpenData && option.staffId">
                      <open-data :openid="option.staffId"></open-data>
                    </template>
                    <template v-else>{{option.label}}</template>
                  </div>
                </template>
              </base-select>
            </template>

          </el-form-item>

          <el-form-item label="通知中的信息">
            <el-select v-model="qrcode.mainQueryKeys" @change="mainQueryKeysHandler($event, 'qrcode')" multiple placeholder="请选择">
              <el-option
                v-for="item in queryQrcodeList"
                :label="item.name"
                :value="item.queryKey"
                :key="item.id"
              >
              </el-option>
            </el-select>                          
          </el-form-item>
          <div class="save-report">
            <el-button type="primary" @click="saveReport('qrcode')" :disabled="pending">保存</el-button>
          </div>
        </el-form>
      
      </div>
      <!-- 个人日报 -->
    
      <!-- 设置发送时间 -->
      <div class="setting-sub-manage" style="margin:0;">
        <div class="setting-title-content">
          设置发送时间
          <el-tooltip content="每日订阅的数据均为统计的昨日数据，不包括今日数据。" placement="top">
            <i class="iconfont icon-fdn-info"></i>
          </el-tooltip>
        </div>

        <el-form label-position="top">
          <el-form-item class="work-time" label="设置日报的发送时间">
            <el-select v-model="reportSendTime" @change="reportSendTimeHandler" placeholder="请选择">
              <el-option :value="item.value" :label="item.label" v-for="(item, idx) in reportSendTimeList" :key="idx"></el-option>
            </el-select>
            <el-button type="primary" @click="openWorkTime">设置工作日</el-button>
          </el-form-item>
        </el-form>
      
      </div>
    <!-- 设置发送时间 -->
    
    </div>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { storageGet } from '@src/util/storage.ts';
import * as ApproveApi from '@src/api/ApproveApi';
import * as SettingApi from '@src/api/SettingApi';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
export default {
  name: 'sub-manage',
  props: {
    showNav: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      isOpenData,
      isFromSetting: false,
      nowMenu: 1,
      newMenuList: this.getTabList(),
      pending: false,
      defaultManager: {
        mainQueryKeys: [],
        queryKeys: [],
        group: 'role',
        groupIds: [],
        id: '',
        module: 'manager',
      },
      defaultTag: {
        mainQueryKeys: [],
        queryKeys: [],
        groupIds: [],
        id: '',
        module: 'tag',
      }, 
      defaultPersonal: {
        mainQueryKeys: [],
        queryKeys: [],
        group: 'role',
        groupIds: [],
        id: '',
        module: 'personal'
      }, 
      defaultQrcode: {
        mainQueryKeys: [],
        queryKeys: [],
        group: 'role',
        groupIds: [],
        id: '',
        module: 'qrcode',
        userList: []
      }, 
      currentSetting: {
        manager: this.defaultManager,
        tag: this.defaultTag,
        personal: this.defaultPersonal,
        qrcode: this.defaultQrcode
      },
      queryList: [],
      roles: [],
      allotSubList: [],
      poolSubList: [],
      auditSubList: [],
      reviewSubList: [],
      reportSendTime: '',
      reportSendTimeList: [
        {
          value: '07:00:00', 
          label: '7:00'
        }, 
        {
          value: '08:00:00', 
          label: '8:00'
        }, 
        {
          value: '09:00:00', 
          label: '9:00'
        }, 
        {
          value: '10:00:00', 
          label: '10:00'
        }, 
      ],
      isQrcodeSetting: false
    }
  },
  computed: {
    queryManagerList() {
      return this.queryList.filter(item=>item.module == 'manager'); 
    },
    queryTagList() {
      return this.queryList.filter(item=>item.module == 'tag'); 
    },
    queryPersonalList() {
      return this.queryList.filter(item=>item.module == 'personal'); 
    },
    queryQrcodeList() {
      return this.queryList.filter(item=>item.module == 'qrcode'); 
    },
    manager(){
      return this.currentSetting.manager || this.defaultManager;
    },
    tag(){
      return this.currentSetting.tag || this.defaultTag;
    },
    personal(){
      return this.currentSetting.personal || this.defaultPersonal;
    },
    qrcode() {
      return this.currentSetting.qrcode || this.defaultQrcode;
    }
  },
  async created () {
    this.newMenuList = await this.getTabList()
    this.nowMenu = this.newMenuList.findIndex(item=>item.id === 'subManage')
    this.getSubManageInfo();
  },
  methods: {
    async getSubManageInfo(){
      try {
        const { status, data, message } = await SettingApi.getSubManageInfo();
        if(status) return this.$platform.notification({
          title: '失败',
          message: message || '',
          type: 'error'
        })
        this.allotSubList = (data.allotSubList || []).map(item => this.handleUserSelect(item)); 
        this.poolSubList = (data.poolSubList || []).map(item => this.handleUserSelect(item));  
        this.auditSubList = (data.auditSubList || []).map(item => this.handleUserSelect(item)); 
        this.reviewSubList = (data.reviewSubList || []).map(item => this.handleUserSelect(item)); 
        this.queryList = data.queryList || [];
        this.isQrcodeSetting = data.qrCodeReport; 
        this.currentSetting = data.dailyReportSetting || {};
        // currentSetting = {'manager':{'group':'role', 'groupIds':['1'], 'id':137, 'mainQueryKeys':['manager_unfinishedTask', 'manager_todayPlanTask', 'manager_yesterdayFinishedTask'], 'module':'manager', 'queryKeys':['manager_unfinishedTask', 'manager_todayPlanTask', 'manager_yesterdayFinishedTask'], 'sendTime':3600000, 'sendTimeStr':'09:00:00', 'tenantId':'520f8a62-e3ac-11ea-b4de-00163e158f63'}, 'personal':{'group':'role', 'groupIds':['1', '2'], 'id':138, 'mainQueryKeys':['personal_todayPlanTask', 'personal_yesterdayFinishedTask', 'personal_exceptionTask'], 'module':'personal', 'queryKeys':['personal_yesterdayFinishedTask', 'personal_exceptionTask', 'personal_goodDegreeRateTaskRank'], 'sendTime':3600000, 'sendTimeStr':'09:00:00', 'tenantId':'520f8a62-e3ac-11ea-b4de-00163e158f63'}, 'tag':{'group':'tag', 'groupIds':['f71e5662-e792-11ea-b4de-00163e158f63', '1d483286-5ac7-11eb-bf98-506b4b2344c4', 'd7ee69f3-4f24-11eb-b4de-00163e158f62', '4b2d74e0-4337-11eb-b4de-00163e158f62', '5177a379-2faf-11eb-b4de-00163e158f62', '34991245-5acb-11eb-bf98-506b4b2344c4', '13fefe68-5ac3-11eb-bf98-506b4b2344c4', '073009ba-5ac3-11eb-bf98-506b4b2344c4', '36dfb875-4f25-11eb-b4de-00163e158f62', 'f1ff92fc-5bdf-11eb-bf98-506b4b2344c4', 'dcbc704e-4f04-11eb-b4de-00163e158f62', '9f9086de-4b66-11ec-8a32-506b4beebeee', '9d6eab75-0fe5-11ec-8a32-506b4beebeee'], 'id':139, 'mainQueryKeys':['tag_unfinishedTask', 'tag_todayPlanTask', 'tag_yesterdayFinishedTask'], 'module':'tag', 'queryKeys':['tag_unfinishedTask', 'tag_todayPlanTask', 'tag_yesterdayFinishedTask'], 'sendTime':3600000, 'sendTimeStr':'09:00:00', 'tenantId':'520f8a62-e3ac-11ea-b4de-00163e158f63'}}
        if(JSON.stringify(this.currentSetting) === '{}'){
          // 空对象
          this.currentSetting = {
            manager: {
              mainQueryKeys: [],
              queryKeys: [],
              group: 'role',
              groupIds: [],
              id: '',
              module: 'manager',
            },
            tag: {
              mainQueryKeys: [],
              queryKeys: [],
              groupIds: [],
              id: '',
              module: 'tag',
            },
            personal: {
              mainQueryKeys: [],
              queryKeys: [],
              group: 'role',
              groupIds: [],
              id: '',
              module: 'personal'
            },
            qrcode: {
              mainQueryKeys: [],
              queryKeys: [],
              group: 'role',
              groupIds: [],
              id: '',
              module: 'qrcode',
              userList: []
            }
          }
        }
        let allTags = data.allTags || [];
        if(!this.currentSetting.manager) {
          this.currentSetting.manager = this.defaultManager;
        } else {
          if(this.currentSetting.manager.group === 'tag') {
            let groupIds = this.currentSetting.manager.groupIds || [];
            if(groupIds.length) {
              this.currentSetting.manager.groupIds = groupIds.map(id=> { 
                const tag = {};
                tag.id = id;
                tag.tagName = this.getTagName(id, allTags)
                return tag;
              })
            }
          }
        }
        if(!this.currentSetting.tag) {
          this.currentSetting.tag = this.defaultTag
        } else {
          let groupIds = this.currentSetting.tag.groupIds || [];
          if(groupIds.length) {
            this.currentSetting.tag.groupIds = groupIds.map(id=> { 
              const tag = {};
              tag.id = id;
              tag.tagName = this.getTagName(id, allTags)
              return tag;
            })
          }
        }
        if(!this.currentSetting.personal) {
          this.currentSetting.personal = this.defaultPersonal
        } else {
          if(this.currentSetting.personal.group === 'tag') {
            let groupIds = this.currentSetting.personal.groupIds || [];
            if(groupIds.length) {
              this.currentSetting.personal.groupIds = groupIds.map(id=> { 
                const tag = {};
                tag.id = id;
                tag.tagName = this.getTagName(id, allTags)
                return tag;
              })
            }
          }
        }
        if(this.isQrcodeSetting) {
          if(!this.currentSetting.qrcode) {
            this.currentSetting.qrcode = this.defaultQrcode
          } else {
            if(this.currentSetting.qrcode.group === 'tag') {
              let groupIds = this.currentSetting.qrcode.groupIds || [];
              if(groupIds.length) {
                this.currentSetting.qrcode.groupIds = groupIds.map(id=> { 
                  const tag = {};
                  tag.id = id;
                  tag.tagName = this.getTagName(id, allTags)
                  return tag;
                })
              }
            }else {
              let userList = this.currentSetting.qrcode.userList || [];
              this.currentSetting.qrcode.userList = userList.map(item => this.handleUserSelect(item)); 
            }
          }
        }
        this.roles = data.allRoles || [];
        this.reportSendTime = data.reportSendTime;
      } catch (error) {
        console.log(error);
      }
    },
    getTagName(id, tags){
      return tags.find(item=>item.id === id).tagName
    },
    handleUserSelect(user) {
      if(!user) return {}
      let { displayName, userId } = user
      return Object.freeze({
        label: displayName,
        value: userId,
        ...user
      })
    },
    async saveReport(module){
      try {
        const params = JSON.parse(JSON.stringify(this.currentSetting[module])) 
        let limitLength = 4
        if(module == 'qrcode') {
          limitLength = 6
        }
        if(params.mainQueryKeys.length >= limitLength) return this.$platform.notification({
          title: '保存失败',
          message:`通知中的信息最多维护${limitLength-1}条`,
          type: 'error'
        })
        if(params.group === 'tag' || params.module === 'tag') {
          params.groupIds = params.groupIds.map(item=>item.id)
        }
        if(params.group === 'person') {
          params.groupIds = params.userList.map(item=>item.userId)
        }
        const { status, message } = await SettingApi.saveDailyReportSetting(params)
        if (status !== 0) return this.$platform.notification({
          title: '保存失败',
          message: message || '',
          type: 'error'
        })
      } catch (error) {
        console.log(error);
      }
    },
    selectRoleOrTag(group, module){
      if(module === 'manager' || module === 'personal' || module === 'qrcode') {
        if(!this.currentSetting[module]) {
          this.currentSetting[module] = module === 'manager' ? this.defaultManager : (module === 'personal' ? this.defaultPersonal : this.defaultQrcode)
        }
      }
      if(group == 'person') {
        this.currentSetting[module].group = group
        this.currentSetting[module].userList = []
      }
      this.currentSetting[module].group = group
      this.currentSetting[module].groupIds = []
    },
    queryKeysHandler(value, module){
      this.currentSetting[module].queryKeys = value 
    },
    mainQueryKeysHandler(value, module){
      this.currentSetting[module].mainQueryKeys = value 
    },
    fetchTeam(params = {}){
      params.type = ''
      return this.$http.post('/security/tag/tree', {...params})
    },
    update(value, module){
      if(!this.currentSetting[module]) {
        if(module === 'manager') {
          this.currentSetting[module] = this.defaultManager
        } else if(module === 'tag') {
          this.currentSetting[module] = this.defaultTag
        } else if(module === 'personal'){
          this.currentSetting[module] = this.defaultPersonal
        }else {
          this.currentSetting[module] = this.defaultQrcode
        }
      }
      if(module == 'qrcode') return this.currentSetting[module].userList = value
      this.currentSetting[module].groupIds = value
    },
    async reportSendTimeHandler(reportSendTime){
      // console.log(reportSendTime);
      try {
        const { status, message } = await SettingApi.setReportSendTime({ reportSendTime })
        if (status !== 0) return this.$platform.notification({
          title: '设置发送时间失败',
          message: message || '',
          type: 'error'
        })
        
      } catch (error) {
        console.log(error);
      }
    },
    openWorkTime(){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: 'setting_workTime',
      //   title: '工作信息维护',
      //   close: true,
      //   url: '/foundation/account/workTime',
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageFeSettingWorkTime,
        fromId
      })
    },
    async remoteMethodList(e){
      return ApproveApi.getInitiatorList({keyword: e.keyword, pageNum: e.pageNum, pageSize: e.pageSize})
        .then(res => {
          if (!res || !res.list) return;
          res.list = res.list.map(item => Object.freeze({
            label: item.displayName,
            value: item.userId,
            ...item
          }))
          return res;
        })
        .catch(err => console.info('searchInitiator function catch err', err))
    },
    updateUser(value, model) {
      this[model] = value
    },
    async saveSubManage(model){
      // fix 17703 人员清空也保存
      // if(!this[model].length) return
      let ids = this[model].map(item=>item.userId).join(',')
      const map = {
        'allotSubList': 'taskAllot',
        'poolSubList': 'taskPool',
        'auditSubList': 'taskAudit',
        'reviewSubList': 'taskReview',
      }
      try {
        const { status, message } = await SettingApi.saveSubManage({ ids, model: map[model] } )
        if (status !== 0) return this.$platform.notification({
          title: '保存失败',
          message: message || '',
          type: 'error'
        })
      } catch (error) {
        console.log(error);
      }
    },
    async getTabList() {
      let messageModules = []
      try {
        messageModules = await storageGet('setting-modules', '[]', 'keyvaluepairs');
        
      } catch (error) {
        console.log(error);
      }
      return [
        {
          id: 'ddmessage',
          name: '消息设置',
          icon: 'icon-bell-fill',
          url: '/foundation/setting/message',
          show: this.isModuleShow('MESSAGE_DD_MESSAGE', messageModules)
        },
        {
          id: 'subManage',
          name: '订阅通知管理',
          icon: 'icon-dingyue',
          url: '/setting/message/subManage',
          show: this.isModuleShow('MESSAGE_SUB_MANAGE', messageModules)
        },
        {
          id: 'smsmessage',
          name: '短信消息设置',
          icon: 'icon-fuwubeizhu',
          url: '/setting/message/smsmessage',
          show: this.isModuleShow('MESSAGE_SMS_MESSAGE', messageModules)
        },
        {
          id: 'emailMessage',
          name: '邮件消息设置',
          icon: 'icon-mail-fill1',
          url: '/foundation/emailMessage',
          show: this.isModuleShow('MESSAGE_EMAIL_MESSAGE', messageModules)
        },
        {
          id: 'toastList',
          name: '消息记录',
          icon: 'icon-xitongrizhi',
          url: '/setting/doMyself/toastList', // 该页面是vue页面
          show: this.isModuleShow('MESSAGE_TOAST_LIST', messageModules)
        },
      ].filter(item=>item.show);
    },
    isModuleShow(moduleId, messageModules){
      let flag = false;
      for (let index = 0; index < messageModules.length; index++) {
        if(messageModules[index].itemName === moduleId) {
          flag = true;
          break;
        }
      }
      return flag;  
    },
    changePage(item, index) {
      if (this.nowMenu === index) {
        return;
      }
      let href = ''
      if(item.url.indexOf('/foundation/') > -1) {
        href = item.url;
      } else {
        href = `${this.$resourcePrefix}${item.url}`;
      }
      window.location.href = href;
      this.nowMenu = index;
    },
  },
}
</script>

<style lang="scss">
.setting-sub-manage-container {
  padding: 16px;
  position: relative;
  box-sizing: border-box;
  height: 100vh;
  max-width: 100vw;
  width:100%;
  display: flex;
  align-items: flex-start;
  .left-menu {
    display: none;
    box-sizing: border-box;
    border-radius: 4px;
    background: #fff;
    width: 194px;
    min-width: 194px;
    height: 100%; 
    .menu-title {
      padding: 0 16px;
      line-height: 48px;
      margin: 0;
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #262626;
    }
    .menu-list {
      padding: 0 16px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color:  #595959;
      line-height: 40px;
      text-decoration: none;
      cursor: pointer;
      display: flex;
      align-items: center;
      &:hover {
        color:#595959;
        background-color: rgba(0, 0, 0, 0.0392156863);
      }
      &.menu-checked {
        background-color: $color-primary-light-1;
        color: $color-primary-light-6;
      }
      span {
        font-size: 14px;
      }
      .icon-box {
        width: 22px;
        height: 22px;
        display: flex;
        align-items: center;
        margin-right: 10px;
        i{
          font-size: 14px;
        }
      }
    }
    
  }
  .main {
    margin-left: 10px;
    flex: 1;
    box-sizing: border-box;
    height: 100%;
    overflow-y: auto;
    border-radius: 4px;
    button {
      height: 32px;
    }
    .setting-sub-manage {
      background: #fff;
      border-radius: 4px;
      margin-bottom: 12px;
      .tip {
        font-size: 14px;
        margin-bottom: 4px;
      }
    }
    
    .setting-title-content {
      cursor: pointer;
      border-bottom: 1px solid #f0f0f0;
      font-weight: 700;
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      line-height: 24px;
      color: #262626;
      padding: 12px 16px;
      margin: 0;
      .margin-t10 {
        margin-top: 20px;
      }
      .iconfont{
        color:#8C8C8C;
        margin-left:5px;
      }
    }

    .setting—box-multiple {
      display: flex;
      padding:12px 16px 24px;
      .biz-form-remote-select{
        margin-right: 12px;
      }
      .base-select-container {
        width: 100%;
        margin-right: 12px;
      }
    }
    .el-form{
      padding:12px 16px 24px;
    }

    .work-time {
      align-items: center;
      margin-bottom: 0;
      button {
        margin-left: 8px;
      }
    }
    .report-department {
      .biz-team-select-clear {
        top: 0;
      }
      .el-form-item {
        display: flex;
        .el-form-item__content {
          display: flex;
          flex: 1;
        }
      }
      .el-dropdown, label {
        width: 150px;
        text-align: left;
      }
      .el-select {
        width: 100%;
        flex: 1;
      }
      .save-report {
        display: flex;
        justify-content: flex-end;
      }
    }
  }  
}

.setting-sub-manage-container {
  
  .base-select-main-content {
    overflow: hidden;
  }
  
  .base-select-container {
    
    .el-input__suffix {
      top: 1px;
      right: 15px;
    }
    
  }
  
  .base-select-container .clearable-layout {
    padding-right: 40px;
  }
}
.base-select-wrap {
  flex: 1
}
</style>